package com.ggy.babybed.wilddog;

import android.content.Context;
import android.util.Log;

import com.wilddog.client.DataSnapshot;
import com.wilddog.client.ValueEventListener;
import com.wilddog.client.Wilddog;
import com.wilddog.client.WilddogError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by ggy on 2016/4/9.
 */
public class CustomWilddog {

    public static final String TAG="CustomWilddog";

    private Wilddog wilddog;
    private boolean tag;
    private Context mContext;
    private Boolean mDebug=true;
    private HashMap<String,List<WildDogDataChange>> mListenMap=new HashMap<>();

    public CustomWilddog(Context context) {
        this.mContext=context;
        Wilddog.setAndroidContext(context);
    }

    public Wilddog getDefWilddogRef(){
        if(null == wilddog){
            wilddog = new Wilddog(WildDogNode.MAIN_NODE);
            wilddog.setAndroidContext(mContext);
        }
        return wilddog;
    }

    /**
     *
     * @param node 存储的节点
     * @param value
     * @return true：set success, false:set failed
     */
    public boolean setValue(String node, Object value){
        if(null == wilddog){
            getDefWilddogRef();
        }
        wilddog.child(node).setValue(value, new Wilddog.CompletionListener() {
            @Override
            public void onComplete(WilddogError wilddogError, Wilddog wilddog) {
                tag = null == wilddogError;
                Log.e(TAG, wilddogError == null ? "set success." : wilddogError.getDetails());
            }
        });
        return tag;
    }

    public void refeshNode(String node) {
        if(null == wilddog){
            getDefWilddogRef();
        }
        wilddog.child(node).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                // 执行相应的处理。 只会被触发一次。
            }
            @Override
            public void onCancelled(WilddogError error) {

            }
        });
    }

    public boolean startListenForNode(String node){
        if(mDebug){
            Log.i(TAG,"start the node for listen :"+node);
        }
        if(!mListenMap.containsKey(node)){
            mListenMap.put(node,new LinkedList<WildDogDataChange>());
        }else{
            Log.i(TAG,"node is yijing statrt!");
            return true;
        }
        listenData(node);
        return true;
    }

    public boolean stopListenForNode(String node){
        return true;
    }

    /**
     * 增加对节点node的监听
     * @param node
     * @param dc
     */
    public void addListenForNode(String node,final WildDogDataChange dc){
        if(mDebug){
            Log.i(TAG,"add the node for listen :"+node);
        }
        if(!mListenMap.containsKey(node)){
            mListenMap.put(node,new LinkedList<WildDogDataChange>());
        }
        if(mListenMap.get(node).contains(dc)){
            return;
        }
        mListenMap.get(node).add(dc);
        Log.i(TAG,"node len is :"+node+" "+ mListenMap.get(node).size()+" listsize: "+mListenMap.size());
    }

    public void rmListenForNode(String node,final WildDogDataChange dc){
        if(mDebug){
            Log.i(TAG,"rm the node for listen :"+node);
        }
        if(!mListenMap.containsKey(node)){
            Log.i(TAG,"no this listen ");
            return;
        }
        if(mListenMap.get(node).contains(dc)){
            mListenMap.get(node).remove(dc);
        }
    }

    public void notifyallListenforNode(String node,List<Object> data){
        if(mDebug){
            Log.i(TAG,"notify the next node for listen :"+data);
        }
        if(mListenMap.containsKey(node)){
            int len = mListenMap.get(node).size();
            Log.i(TAG,"notify the node for listen len :"+len);
            for(int j=0;j<len;j++){
                mListenMap.get(node).get(j).onchange(data);
            }
        }
    }

    public boolean listenData(String node){
        if(null == wilddog){
            getDefWilddogRef();
        }
        wilddog.child(node).addValueEventListener(new MyValueEventListener(node) {
            List<Object> list = new ArrayList<>();
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(dataSnapshot.getValue() instanceof List) {
                    list.addAll((List) dataSnapshot.getValue());
                }else if(dataSnapshot.getValue() instanceof Map){
                    list.addAll(((Map) dataSnapshot.getValue()).values());
                }else{
                    list.add(dataSnapshot.getValue());
                }
                notifyallListenforNode(Node,list);
            }

            @Override
            public void onCancelled(WilddogError wilddogError) {
                if(null != wilddogError){
                    Log.e(TAG, wilddogError.getCode() + wilddogError.getDetails());
                    tag = false;
                }else{
                    tag = true;
                }
            }
        });
        return tag;
    }

    public abstract  class MyValueEventListener implements  ValueEventListener{

        public String Node;
        public MyValueEventListener(String node){
            this.Node=node;
        }
    }

}
